<template>
  <a-card title="库存清单">
    <a-input-search v-model:value="keyword"
                    allow-clear
                    enter-button
                    placeholder="根据书名检索"
                    style="width: 50%"
                    @search="onSearch"></a-input-search>
    <a-divider type="horizontal"/>
    <a-table
      :columns="columns"
      :data-source="list"
      :pagination="pagination"
      :rowClassName="(record, index) => index % 2 === 1 ? 'table-striped' : null"
      :rowKey="record => record._id"
      bordered
      class="ant-table-striped"
      @change="handleTableChange"
    >
      <template #status="{text}">
        <span>
          <a-tag
            :color="text.quantity > 0 ? 'green' : 'volcano'"
          >
            {{ text.quantity > 0 ? '有现货' : '缺货' }}
          </a-tag>
        </span>
      </template>
      <template #actions="{text}">
        <a @click="handleInput(text)">入库</a>
        <a-divider type="vertical"/>
        <a @click="handleOutput(text)">出库</a>
      </template>
    </a-table>
  </a-card>
  <a-modal
    v-model:visible="visible"
    :confirm-loading="confirmLoading"
    :title="textMap[dialogStatus]"
    @ok="handleOk"
  >
    <a-input-number
      v-model:value="inputNumber"
      :min="0"
      style="width: 100%;"
    />
  </a-modal>
</template>

<script>
import { Card, Divider, Input, InputNumber, message, Modal, Table, Tag } from 'ant-design-vue'
import { computed, onMounted, reactive, ref } from 'vue'
import { fetchBookList, updateBook } from '@/api/book'
import { deepClone } from '@/utils'

const defaultFormData = {
  id: '',
  quantity: 0,
}

export default {
  name: 'index',
  components: {
    ATable: Table,
    ACard: Card,
    AInputNumber: InputNumber,
    AInputSearch: Input.Search,
    ADivider: Divider,
    ATag: Tag,
    AModal: Modal,
  },
  setup () {
    const columns = [
      {
        title: '图书名称',
        dataIndex: 'name',
      },
      {
        title: '图书类别',
        dataIndex: 'type',
      },
      {
        title: 'ISBN',
        dataIndex: 'ISBN',
      },
      {
        title: '出版社',
        dataIndex: 'press',
      },
      {
        title: '状态',
        slots: {
          customRender: 'status',
        },
      },
      {
        title: '库存数量',
        dataIndex: 'quantity',
      },
      {
        title: '操作',
        slots: {
          customRender: 'actions',
        },
      },
    ]
    let currentPage = ref(1)
    let pageSizeRef = ref(5)
    let keyword = ref('')
    let list = ref([])
    let total = ref(0)
    let size = ref(5)
    let inputNumber = ref(0)
    let dialogStatus = ref('')
    let textMap = reactive({
      input: '入库数目',
      output: '出库数目',
    })
    const formData = reactive(deepClone(defaultFormData))
    const visible = ref(false)
    const confirmLoading = ref(false)

    const pagination = computed(() => ({ // 此处意为：直接返回一个对象，小括号是优先级的意思，先执行小括号内部的
        total: total.value,
        current: currentPage.value,
        pageSize: size.value,
      }),
    )
    onMounted(async () => {
        await getList()
      },
    )
    const handleTableChange = async ({ current, pageSize }) => {
      currentPage.value = current
      size.value = pageSize
      await getList()
    }
    const getList = async () => {
      await fetchBookList({
        page: currentPage.value,
        size: pageSizeRef.value,
        keyword: keyword.value,
      }).then(res => {
          list.value = res.data.list
          total.value = res.data.total
        },
      )
    }
    const onSearch = () => {
      getList()
    }
    const handleInput = (record) => {
      dialogStatus.value = 'input'
      formData.id = record._id
      formData.quantity = record.quantity
      visible.value = true
    }
    const handleOutput = (record) => {
      dialogStatus.value = 'output'
      formData.id = record._id
      formData.quantity = record.quantity
      visible.value = true
    }
    const handleOk = async () => {
      confirmLoading.value = true
      const temp = deepClone(formData)
      if (dialogStatus.value === 'output' && temp.quantity >= inputNumber.value) {
        temp.quantity -= inputNumber.value
      } else if (dialogStatus.value === 'output' && temp.quantity < inputNumber.value) {
        message.warning('出库数不能超过库存数')
        confirmLoading.value = false
        return
      } else {
        temp.quantity += inputNumber.value
      }
      await updateBook(temp).then(res => {
        message.success(res.msg)
        visible.value = false
        confirmLoading.value = false
      })
      await getList()
      Object.assign(formData, defaultFormData)
    }

    return {
      columns,
      textMap,
      dialogStatus,
      list,
      keyword,
      visible,
      confirmLoading,
      inputNumber,
      pagination,
      handleTableChange,
      handleInput,
      handleOutput,
      handleOk,
      onSearch,
    }
  },
}
</script>

<style lang="scss" scoped>
//noinspection CssInvalidPseudoSelector
.ant-table-striped :deep(.table-striped) {
  background-color: #fafafa;
}

/* to prevent the arrow overflow the popup container,
or the height is not enough when content is empty */
.numeric-input .ant-tooltip-inner {
  min-width: 32px;
  min-height: 37px;
}

.numeric-input .numeric-input-title {
  font-size: 14px;
}
</style>
